require 'utils'

include SulpetUtils

class Attendee < ActiveRecord::Base

    #baita gambiarra
    attr_accessor :old_gd, :old_lodge
    attr_accessor :gambi

	#############################
	# singleton methods			#
	#############################
  def self.total
		@total ||= Attendee.count
	end

    def self.lodge
        @lodge ||= Attendee.find(:all,:conditions => { :lodge => true } )
    end

	def self.lodge_total
		Attendee.lodge.size
	end

  def self.lodge_full
        lodge_total >= max_lodge_size
  end

	def self.shirts
		@shirts ||= Attendee.find(:all,:conditions => { :shirt => true} )
	end

  def self.shirts_total
      Attendee.shirts.size
  end

	def self.tutors
		@tutors ||= Attendee.find(:all, :conditions => { :tutor => true })
	end

  def self.paid
      @paid ||= Attendee.find(:all, :conditions => { :paid => true })
  end

  def self.paid_total
      Attendee.paid.size
  end

  def self.paid_lodge_total
      (Attendee.paid & Attendee.lodge).size
  end

  def self.queue
    @queue ||= Attendee.find(:all, :conditions => { :queue => true })
  end

  def self.queue_total
    Attendee.queue.size
  end

	def self.max_lodge_size
		406
	end

	def self.total_gds
		10
	end

  def self.max_capacities current_gd
      { 0 => 30, 9 => 30,5 => 50 ,3 => 75}[current_gd] || 40
  end

  def self.attendees_gd current_gd
  	Attendee.find(:all, :conditions => { :gd => current_gd } )
  end

  def self.gd_attendees current_gd
    Attendee.count(:conditions => { :gd => current_gd } )
  end

	def self.expire_cache
		logger.info "Cache expired, cuz a new attendee registered or was edited."
		@total = nil
		@lodge = nil
		@shirt = nil
    @paid = nil
		@tutors = nil
		@queue = nil
	end

	def before_save
		correct_pet_name
		set_boolean_fields
	end

	def set_boolean_fields
		shirt ||= false
		tutor ||= false
		paid  ||= false
		lodge ||= false
		queue ||= false
		true
	end


  ##############################
  # utilities                  #
  ##############################
	def lodge_capacity
		if (old_lodge != lodge) and lodge and Attendee.lodge_total >= Attendee.max_lodge_size
			errors.add("lodge","full")
		end
	end

  def gds_capacity

        if !gd.nil? and old_gd != gd
          if Attendee.gd_attendees(gd) >= Attendee.max_capacities(gd)
            errors.add("GD","está com as vagas esgotadas. No caso de não conseguir se cadastrar em nenhum GD, selecione a primeira opção da lista (a opção vazia).")
          end
        end

  end

  def correct_pet_name
    reg = /^([pP][eE][tT])\W+(.*)$/
    data = reg.match(self.pet.strip.squeeze)

    if data
      self.pet = data[2]
    end
  end

  def get_encoded_email
    enc = {
      '@' => " [ at ] ",
      '.' => " [ dot ] ",
    }

    return_email = get_email

    enc.each { |k,v| return_email.gsub!(k,v) }

    return_email
  end

  def get_email
    User.find(:all, :conditions => {:login => user_login } )[0].email
  end


  def has_form?
  	Form.find_by_attendee_id(id) ? true : false
  end

  #########################
  # pagination			  #
  #########################
  cattr_reader :per_page
  @@per_page = 20

  ##########################
  #	associations           #
  ##########################
  has_one :form

  ##########################
  #	validations	           #
  ##########################
  [:name, :city, :rg, :pet, :uf, :ies, :neighborhood, :cep, :cpf].each do |a|
    validates_presence_of a, :message => 'missing'
  end

  validate :lodge_capacity
  validate :gds_capacity

  validates_length_of :name, :maximum => 60, :message => 'long'
  validates_length_of :city, :maximum => 30, :message => 'long'
  validates_length_of :rg, :maximum => 10, :message => 'long'
  validates_length_of :pet, :maximum => 30, :message => 'long'
  validates_length_of :ies, :maximum => 30, :message => 'long'
  validates_length_of :neighborhood, :maximum => 60, :message => 'max'

  validates_length_of :cep, :is => 8, :message => 'length'
  validates_format_of :cep, :with => /^[0-9]+$/, :message => 'format'

  validates_uniqueness_of :rg, :message => 'unique'

  validates_length_of :cpf, :is => 11, :message => 'length'
  validates_uniqueness_of :cpf, :message => 'unique'

  validates_format_of :cpf, :with => /^[0-9]+$/ , :if => Proc.new { |a| !(validate_cpf a.cpf) } , :message => 'format'

end
